// pages/home/home.js 
import WxValidate from "../../utils/wxValidate.js";
var common = require("../../utils/public.js") //引入public.js脚本
var api = require("../../utils/api");
var config = require("../../config.js");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    array: [],
    selectorIndex: 0,
    // 门店照片
    imgBoard: [],
    // 营业执照
    imgStore: [], 
    // 牌匾照片
    plaquePicUrl: [],
    // 收货地址
    mapAddr: {},
    // 图片显示
    boardShow: true,
    storeShow: true,
    plaqueBoard: true,
    //城市编号
    cityId: "",
    // 用户id
    userInfoId: "",
    //店铺类型id 
    type: "",
    newAdd:null,
    form: {
      store: "",
      consignee: "",
      linkTel: "",
      address: "",
      buildNO: "",
      codes: "",
    },
    plaquePic: "", //营业照片
    shopPic: "", //门店照片
    licensePic: "", //牌匾照片
  },
  bindPickerChange: function(e) {
    let addrs = "form.address";
    this.setData({
      selectorIndex: e.detail.value,
      [addrs]: "",
      mapAddr: {}
    })

  },
  onShow: function() {
    // 获取城市id
    let cityId = wx.getStorageSync('cityId');
    //获取用户id
    let userInfoId = wx.getStorageSync('openId');
    this.setData({
      cityId,
      userInfoId
    })
    //收货地址
    this.mapAddr();
  },
  mapAddr() {
    let {
      address
    } = this.data.form;
    let {
      mapAddr
    } = this.data;
    let addressInfo = mapAddr.addressInfo;
    if (addressInfo && JSON.stringify(addressInfo) != "{}") {
      //省市区...
      let address = mapAddr.newWhere;
      let mapAdd = "form.address";
      this.setData({
        [mapAdd]: address
      })
    }
  },
  onLoad: function(options) {
    // 店铺类型传过来的参数
    let that = this;
    that.setData({
      type: options.id,
      newAdd: options.newAdd
    })
    api.cityList({
      page: {
        size: 6,
        current: 0,
        isStartPage: false,
        pages: 1,
      }
    }).then(res => {
      if (res.result) {
        let array = that.data.array;
        let selector = res.object.records;
        selector.forEach((v) => {
          array.push(v.name)
        })
        that.setData({
          array
        })
      }
    })
    this.initValidate();
  },
  // 提示信息
  initValidate() {
    let rules = {
      store: {
        required: true
      },
      consignee: {
        required: true,
        minlength: 2
      },
      linkTel: {
        required: true,
        tel: true,
      },
      address: {
        required: true,
        minlength: 2
      },
      buildNO: {
        required: true,
        minlength: 3
      }
    }
    let message = {
      store: {
        required: "请填写门店名",
      },
      consignee: {
        required: "请填写收货人",
        minlength: "请填写正确收货人"
      },
      linkTel: {
        required: "请输入手机号",
        tel: "请输入正确手机号",
      },
      address: {
        required: "请填写收货地址",
        minlength: "请填写正确收货地址"
      },
      buildNO: {
        required: "请填写楼号门牌",
        minlength: "请填写正确楼号门牌"
      }
    }
    this.WxValidate = new WxValidate(rules, message)
  },
  // 表单提交
  handleSubmit: common.throttleFunc(function (e) {
    // 店铺id/地址/用户id/城市编号/门店/营业执照
    let {
      type,
      mapAddr,
      userInfoId,
      cityId
    } = this.data;
    // 经纬度 区域 区域编码
    const {
      latitude,
      longitude,
      district,
      adcode
    } = mapAddr
    // 验证表单/图片url
    let {
      imgBoard,
      imgStore,
      plaquePicUrl,
      plaquePic,
      shopPic,
      licensePic
    } = this.data;

    if (!this.WxValidate.checkForm(e)) {
      let err = this.WxValidate.errorList[0]
      this.showModal(err);
      return false;
    }
    // 门店
    // if (imgBoard && imgBoard.length == 0) {
    //   wx.showModal({
    //     content: "请上传门店照片",
    //     showCancel: false
    //   })
    //   return false;
    // }
    // 营业
    if (imgStore && imgStore.length == 0) {
      wx.showModal({
        content: "请上传营业执照",
        showCancel: false
      })
      return false;
    }
    // 牌匾
    if (plaquePicUrl && plaquePicUrl.length == 0) {
      wx.showModal({
        content: "请上传牌匾照片",
        showCancel: false
      })
      return false;
    }
    // 发送请求
    let infos = {}
    api.formSubmit({
        buildNo: e.detail.value.buildNO, //门牌号
        addr: e.detail.value.address, //地址
        inviteCode: e.detail.value.codes, //邀请码
        linkman: e.detail.value.consignee, //收货人
        linkTel: e.detail.value.linkTel, //收货人电话
        name: e.detail.value.store, //门店名
        type: type, //店铺类型
        latitude: latitude, //纬度
        longitude: longitude, //经度
        cityAddr: mapAddr.district, // 所属区
        cityCode: mapAddr.adcode, // 区码
        userInfoId: wx.getStorageSync("openId"), //用户id
        cityId: wx.getStorageSync("cityId"), //城市编号
        plaquePicUrl: licensePic, ///牌匾照片
        shopPicUrl: shopPic, //门店照片
        licensePicUrl: plaquePic, //营业执照
        addressType: 1 //商铺
      })
      .then(res => {
        if (res.result) {
          if (this.data.newAdd) {
            wx.request({
              url: `${config.url}/admin/user/loginUserType`,
              data: {
                openid: wx.getStorageSync("openId"),
                authUserId: '-1',
                type: 1,
                shopId: '-1'
              },
              header: {
                'content-type': 'application/json',
              },
              method: 'POST',
            })
          }
          // end
          wx.setStorageSync('address', {
            buildNo: e.detail.value.buildNO, //门牌号
            addr: e.detail.value.address, //地址
            linkman: e.detail.value.consignee, //收货人
            linkTel: e.detail.value.linkTel, //收货人电话
            name: e.detail.value.store, //门店名
            type: type, //店铺类型
            latitude: latitude, //纬度
            longitude: longitude, //经度
            cityAddr: mapAddr.district, // 所属区
            cityCode: mapAddr.adcode, // 区码
          })
          wx.showToast({
            title: '提交成功',
            duration: 1500,
            success: () => {
              wx.reLaunch({
                url: '/pages/index/index',
              })
            }
          })
        }
      })
  }),
  // 失败
  showModal(err) {
    wx.showModal({
      content: err.msg,
      showCancel: false
    })
  },
  handleImg(e) {
    let indexs = e.currentTarget.dataset.index;
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        // 添加请求加载等待
        wx.showLoading({
          title: '加载中...',
          mask: true
        })
        //图片本地地址
        let tempFilePaths = res.tempFilePaths;
        //  页面渲染
        let imgStore = JSON.parse(JSON.stringify(that.data.imgStore));
        let imgBoard = JSON.parse(JSON.stringify(that.data.imgBoard));
        let plaquePicUrl = JSON.parse(JSON.stringify(that.data.plaquePicUrl));
        if (indexs === 0) {
          that.setData({
            // 门店
            boardShow: false,
            imgBoard: tempFilePaths
          })
        } else if (indexs === 1) {
          //营业质保
          that.setData({
            storeShow: false,
            imgStore: tempFilePaths
          })
        } else if (indexs === 2) {
          //门店照片
          that.setData({
            plaqueBoard: false,
            plaquePicUrl: tempFilePaths
          })
        }
        // 上传给服务器

        that.uploadFiles(`${config.url}/admin/shopInfoEntity/uploadFile`, tempFilePaths[0], indexs)
      }
    })
  },
  uploadFiles(url, filepath, indexs) {
    // 上传图片到服务器
    let that = this;
    let {
      plaquePic,
      shopPic,
      licensePic
    } = that.data;
    wx.uploadFile({
      url: url,
      filePath: filepath,
      method: "POST",
      name: 'file',
      header: {},
      success: function(res) {
        // 成功

        let url = JSON.parse(res.data).data;
        switch (indexs) {
          case 0:
            that.setData({
              shopPic: url
            })
            break;
          case 1:
            that.setData({
              plaquePic: url
            })
            break;
          case 2:
            that.setData({
              licensePic: url
            })
            break;
        }

      },
      complete: function() {
        // 关闭等待
        wx.hideLoading();
      }
    })
  },
  // 图片预览
  handlePreview(e) {
    //当前图片下标
    let index = e.currentTarget.dataset.index;
    //所有图片
    let {
      imgBoard,
      imgStore,
      plaquePicUrl
    } = this.data;
    if (index === 0) {
      wx.previewImage({
        urls: imgBoard,
        current: imgBoard[index]
      })
    } else if (index === 1) {
      wx.previewImage({
        urls: imgStore,
        current: imgStore[index]
      })
    } else if (index === 2) {
      wx.previewImage({
        urls: plaquePicUrl,
        current: plaquePicUrl[index]
      })
    }
  },
  // 删除图片
  delImg(e) {
    let that = this;
    let {
      imgBoard,
      imgStore,
      plaquePicUrl
    } = this.data;
    // 获取要删除的第几张图片的下标
    const idx = e.currentTarget.dataset.index;
    // splice  第一个参数是下表值  第二个参数是删除的数量

    if (idx === 0) {
      imgBoard.splice(0, 1);
      that.setData({
        imgBoard,
        boardShow: true
      })
    } else if (idx === 1) {
      imgStore.splice(0, 1);
      that.setData({
        imgStore,
        storeShow: true
      })
    } else if (idx === 2) {
      plaquePicUrl.splice(0, 1);
      that.setData({
        plaquePicUrl,
        plaqueBoard: true
      })
    }
  },
  //地址跳转
  maps() {
    let {
      array,
      selectorIndex
    } = this.data;
    if (JSON.stringify(this.data.mapAddr) === '{}') {
      wx.navigateTo({
        url: '/components/my-map/my-map?citys=' + array[selectorIndex],
      })
    } else {
      const {
        latitude,
        longitude,
        newWhere
      } = this.data.mapAddr
      wx.navigateTo({
        url: `/components/my-map/my-map?latitude=${latitude}&longitude=${longitude}&title=${newWhere}&citys=${array[selectorIndex]}`,
      })
    }
  }
})